import { getBaseUrl } from '@/services/urlconst';
import {
  getLevelFirst,
  getLevelZero,
  getUserID,
  requestFunComponFiex,
} from '@/utils';
import { message } from 'antd';
import { useCallback, useState } from 'react';
import { useRequest } from 'umi';
import { ContacterAPI } from '../common/type';

let baseUrl = getBaseUrl();
// let baseUrl = 'http://192.168.3.21:9002'; //小田本地

// 获取用户列表数据
const personalTableService = (curRes: Record<string, any>) => {
  /**保存搜索参数 */
  const [manageTableParams, setManageTableParams] = useState<any>({});
  const tableParamsCallback = useCallback(
    (parObj: any) => {
      setManageTableParams(parObj);
    },
    [manageTableParams],
  );

  const personalTableRequest = useRequest(
    (opt: ContacterAPI.IOwenTableService) => {
      let queryObj = judgmentAuthority(curRes);
      let bodyParams: any = {
        // current: 1,
        // pageSize: 10,
        // sort: 'ownTime',
        ...queryObj,
        ...opt,
      };
      let url = `${baseUrl}/personalController/dataGrid/${bodyParams?.params}`;
      let methodType = 'POST';
      tableParamsCallback(bodyParams);
      return requestFunComponFiex(methodType, url, bodyParams);
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
      onSuccess: (res: any) => {
        if (res && res?.msgFlag) {
          message.success(res?.msg);
        } else {
          message.error(res?.msg);
        }
      },
    },
  );

  const getTableValues = useCallback(
    (otherRequest: ContacterAPI.IOwenTableService | any) => {
      const request: ContacterAPI.IOwenTableService | any = {
        ...otherRequest,
      };
      personalTableRequest?.run({
        ...request,
      });
    },
    [],
  );

  const personalTableData = personalTableRequest.data;

  const personalTableLoading = personalTableRequest.loading;

  return {
    getTableValues,
    personalTableData,
    personalTableLoading,
    manageTableParams,
  };
};

export { personalTableService };

/**
 * 判断权限
 */
const judgmentAuthority = (curRes: Record<string, any>) => {
  if (curRes?.['/personalController/ownCompanyID']) {
    return {
      ownCompanyID: getLevelZero(),
      params: 'ownCompanyID',
      ownType: null,
    };
  } else if (curRes?.['/personalController/ownDepartmentID']) {
    return {
      ownDepartmentID: getLevelFirst(),
      params: 'ownDepartmentID',
      ownType: null,
    };
  } else if (curRes?.['/personalController/ownerID']) {
    return {
      ownerID: getUserID(),
      params: 'ownerID',
      ownType: null,
    };
  }
};
